package com.app.mingluxing.mqtt;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;

import com.app.mingluxing.mqttsource.MqttClient;
import com.app.mingluxing.utils.CommonUtils;
import com.app.mingluxing.utils.LogUtil;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * mqtt服务service
 * Created by Aaron on 15/12/9.
 */
public class MQTTService extends Service {

    private ScheduledExecutorService scheduler;

//    private MqttClient mqttClient;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

//    private static final String topic = "15225087687";

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        LogUtil.e("tag", "====starService====");
//        //连接MQTT
//        new Thread(runnable).start();

//        LogUtil.e("tag", "主线程" + Thread.currentThread().getName());

//        检测是否连接正常
        if (scheduler == null)
            scheduler = Executors.newSingleThreadScheduledExecutor();

        //1,runnable 2,  3,周期 4,时间单位: 秒
//        if (scheduler != null)

//        new Thread(runnable).start();

        scheduler.scheduleAtFixedRate(runnable, 0, 30 * 1000, TimeUnit.MILLISECONDS);

        return super.onStartCommand(intent, START_STICKY, startId);

    }

    private Runnable runnable = new Runnable() {
        @Override
        public void run() {

            LogUtil.e("tag", getClass().getName() + "runnbale 运行检测一次, 线程的名称 : " + Thread.currentThread().getName());

            //网络不可用
            if (!CommonUtils.isNetworkAvailable(getApplicationContext())) {
                return;
            }

            MqttClient mqttClient = MqttManager.getInstance().getMqttClient();

            if (mqttClient == null || !mqttClient.isConnected())
                MqttManager.getInstance().getMqttIp(getApplicationContext());

        }
    };

    @Override
    public boolean stopService(Intent name) {

        LogUtil.e("tag", "====stopService====");

        if (scheduler != null) {
            scheduler.shutdownNow();
            scheduler = null;
        }
        return super.stopService(name);
    }

    @Override
    public void onLowMemory() {

        LogUtil.e("tag", "====onLowMemory===");

    }

    @Override
    public boolean onUnbind(Intent intent) {

        LogUtil.e("tag", "====onUnbind===");

        return super.onUnbind(intent);
    }

//    @Override
//    public void onTrimMemory(int level) {
//
//        LogUtil.e("tag", "====onTrimMemory===");
//
//        super.onTrimMemory(level);
//    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        LogUtil.e("tag", "service === ondestory");

        if (scheduler != null) {
            scheduler.shutdownNow();
            scheduler = null;
        }

    }

}